<?php
// +----------------------------------------------------------------------
// | TOPThink [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://topthink.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Aoiujz <zuojiazi@vip.qq.com>
// +----------------------------------------------------------------------
// | 2012-4-25  SnsSdkAction.class.php
// +----------------------------------------------------------------------

abstract class SnsSdkAction extends Action{
	/**
	 * 当前API对象
	 * @var object
	 */
	private $_api  = null;
	
	/**
	 * 默认调用腾讯微博
	 * 不需要接入多个微博的时候可以修改此参数避免调用授权的时候传递参数weibo
	 * 此属性必须小写
	 * @var string
	 */
	private $_type = 'tencent';
	
	protected function _initialize(){
		$type = $this->_get('sns_type'); //获取当前调用微博的类型
		if($type) $this->_type = strtolower($type);
		
		switch($this->_type){
			case 'tencent':
				import('ORG.SNS_SDK.TencentWeiBo');
				$this->_api = new TencentWeiBo();
				break;
			case 'sina':
				import('ORG.SNS_SDK.SinaWeiBo');
				$this->_api = new SinaWeiBo();
				break;
			case '163':
				import('ORG.SNS_SDK.T163WeiBo');
				$this->_api = new T163WeiBo();
				break;
			default:
				throw_exception("不支持的微博类型:{$this->_type}");
		}
	}
	
	/* 加载SDK 获取授权API 并跳转到授权页面 */
	public function oauthCode(){
		/* 记录进入授权页面的URL */
		cookie('click_sns_login_url',  $_SERVER["HTTP_REFERER"]);
	
		/* 跳转到授权页面 */
		header('Location: ' . $this->_api->getRequestCodeURL());
	} 
	
	/* 授权回调页面 */
	public function callback(){
		/* 调用api获取access_token */
		$this->_api->getAccessToken($this->_get('code'), $this->_get('openid'), $this->_get('openkey'));
	
		/* _init_callback 中如果没有跳转则跳转到配置中指定的业务处理页面 */
		header('Location: ' . U(MODULE_NAME . '/' . C("SNS_SDK_{$this->_type}.SUCCESS"), "sns_type={$this->_type}"));
	}
}
